//
//  WGQFamilyAlbumViewController.m
//  meiang_edu
//
//  Created by JUMIWGQ on 2018/10/1.
//  Copyright © 2018 com.meiang.meiang_edu. All rights reserved.
//

#import "WGQFamilyAlbumViewController.h"
#import "WGQEdgeInsetsLabel.h"
#import "UIView+ShowView.h"
#import "WGQAlbumTableViewCell.h"
//#import "WGQGrowUpLittleModel.h"
#import "WGQFamilyAlbumModel.h"

#define FFColorAlpha(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:0.6]

@interface WGQFamilyAlbumViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * tableArray;
@property (nonatomic,strong) UILabel * saveSuccessLabel;
//@property (nonatomic,copy) NSString * photo_id;//相册id

@end

@implementation WGQFamilyAlbumViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = FFColor(0xebebeb);
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.tableArray = [NSMutableArray array];
    self.title = @"家庭相册";
//    self.photo_id = @"474700ad-5c31-4df7-ab74-fe7b392cec41";
    [self showPromptLabel];
    [self addSubViews];
    [self requestData];
}

- (void)requestData
{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
         request.URLString = [NSString stringWithFormat:@"%@%@",Photo_list,self.photo_id];
         request.methodType = ZBMethodTypeGET;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             if (self.tableArray.count > 0)
             {
                 [self.tableArray removeAllObjects];
             }
             NSArray * array = dataDict[@"value"];
             NSMutableArray * muarray = [NSMutableArray array];
             [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
              {
                  NSDictionary * dict = obj;
                  WGQFamilyAlbumModel * model = [[WGQFamilyAlbumModel alloc] initWithDiction:dict];
                  [muarray addObject:model];
              }];
             [muarray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
              {
                  WGQFamilyAlbumModel * model = obj;
                  __block BOOL isHaveThis = NO;
                  [self.tableArray enumerateObjectsUsingBlock:^(id  _Nonnull obj1, NSUInteger idx1, BOOL * _Nonnull stop1)
                  {
                      NSMutableDictionary * dict = obj1;
                      if ([dict[@"title"] isEqualToString:model.ddate])
                      {
                          [dict[@"array"] addObject:model];
                          isHaveThis = YES;
                      }
                  }];
                  if (isHaveThis == NO)
                  {
                      NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                      [dict setObject:model.ddate forKey:@"title"];
                      NSMutableArray * array = [NSMutableArray array];
                      [array addObject:model];
                      [dict setObject:array forKey:@"array"];
                      [self.tableArray addObject:dict];
                  }
              }];
             
             DLog(@"%@",self.tableArray);
             [self.tableView reloadData];
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);
         
     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];
}

- (void)showSuccessText:(NSString *)text
{
    self.saveSuccessLabel = [[UILabel alloc] init];
    self.saveSuccessLabel.text = text;
    self.saveSuccessLabel.textAlignment = NSTextAlignmentCenter;
    self.saveSuccessLabel.backgroundColor = FFColorAlpha(0x333333);
    self.saveSuccessLabel.font = [UIFont fontWithName:kMainFontFormat size:14 * kScale];
    self.saveSuccessLabel.textColor = [UIColor whiteColor];
    self.saveSuccessLabel.layer.masksToBounds = YES;
    self.saveSuccessLabel.layer.cornerRadius = 7 * kScale;
    [self.view addSubview:self.saveSuccessLabel];
    [self.saveSuccessLabel mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.view.mas_left).offset(4 * kScale);
         make.right.equalTo(self.view.mas_right).offset(-4 * kScale);
         make.height.mas_equalTo(42 * kScale);
         make.bottom.equalTo(self.view.mas_bottom).offset(-12 * kScale);
     }];
    
    // 创建NSTimer对象
    NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    // 加入RunLoop中
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)timerAction
{
    [self.saveSuccessLabel removeFromSuperview];
}

- (void)addSubViews
{
    [self drawRightButton];
    [self drawTableView];
}

- (void)drawTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[WGQAlbumTableViewCell class] forCellReuseIdentifier:[NSString stringWithUTF8String:object_getClassName([WGQAlbumTableViewCell class])]];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 70 * kScale;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.view.mas_left).offset(4 * kScale);
         make.right.equalTo(self.view.mas_right).offset(-4 * kScale);
         make.top.equalTo(self.view.mas_top);
         make.bottom.equalTo(self.view.mas_bottom);
     }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tableArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WGQAlbumTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithUTF8String:object_getClassName([WGQAlbumTableViewCell class])] forIndexPath:indexPath];
    [cell setObject:self.tableArray[indexPath.section]];
    __weak __typeof(&*self)weakSelf = self;
    //图片保存成功的提示
    cell.image_save_success_block = ^(NSString * _Nonnull isSaveSuccess)
    {
        [weakSelf showSuccessText:isSaveSuccess];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 4 * kScale;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)drawRightButton
{
    //右上角的按钮
    UIButton * rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 0.0, 35.0, 35.0)];
    [rightBtn addTarget:self action:@selector(rightBtnActionWithSender:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"reminderbutton_logo"] forState:UIControlStateNormal];
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 35.0, 35.0)];
    [view addSubview:rightBtn];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = rightItem;
}

//右上角按钮的点击事件
- (void)rightBtnActionWithSender:(UIButton *)sender
{
    [self showPromptLabel];
}

- (void)showPromptLabel
{
    //蒙版
    WGQEdgeInsetsLabel * promptLabel = [[WGQEdgeInsetsLabel alloc] init];
    promptLabel.contentInset = UIEdgeInsetsMake(0, 12 * kScale, 0, 12 * kScale);
    promptLabel.text = @"如果您需要删除或添加卡片内容，\n请长按您所需要操作的卡片";
    promptLabel.numberOfLines = 2;
    promptLabel.backgroundColor = FFColor(0xffffff);
    promptLabel.font = [UIFont fontWithName:kMainFontFormat size:14 * kScale];
    promptLabel.textColor = FFColor(0x666666);
    promptLabel.layer.masksToBounds = YES;
    promptLabel.layer.cornerRadius = 7 * kScale;
    [promptLabel showWithFrame:CGRectMake(100 * kScale, 72 * kScale, 236 * kScale, 63 * kScale)];
}

@end
